package com.yksj.healthtalk.ui.friend;

import java.util.ArrayList;
import java.util.List;

import org.handmark.pulltorefresh.library.PullToRefreshBase;
import org.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import org.handmark.pulltorefresh.library.PullToRefreshListView;
import org.json.JSONException;
import org.json.JSONObject;

import sfs2x.client.core.SFSEvent;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.yksj.healthtalk.adapter.SearchAdapter;
import com.yksj.healthtalk.adapter.SearchAdapter.onClickFriendAttentionListener;
import com.yksj.healthtalk.comm.LodingFragmentDialog;
import com.yksj.healthtalk.comm.RootFragment;
import com.yksj.healthtalk.db.ChatUserHelper;
import com.yksj.healthtalk.entity.CustomerInfoEntity;
import com.yksj.healthtalk.entity.MessageEntity;
import com.yksj.healthtalk.net.http.AsyncHttpResponseHandler;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.services.MessagePushService;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.app.AppData;
import com.yksj.healthtalk.ui.app.HTalkApplication;
import com.yksj.healthtalk.ui.doctor.DoctorExactSearchActivity;
import com.yksj.healthtalk.ui.setting.PersonalInformationActivity;
import com.yksj.healthtalk.utils.FriendHttpUtil;
import com.yksj.healthtalk.utils.ToastUtil;
/**
 * 社交场
 * @author Administrator
 *
 */
public class FriendExactSearchFragment extends RootFragment implements
		OnClickListener, OnItemClickListener, OnRefreshListener2<ListView>, onClickFriendAttentionListener {

	private String duomeiNum;
	private PullToRefreshListView mPullToRefreshListView;
	private SearchAdapter adapter;
	private ListView mListView;
	private onBackListener listener;
	ArrayList<CustomerInfoEntity> entities = new ArrayList<CustomerInfoEntity>();
	private int pagenum = 20;
	private int pagesize = 1;
	private Activity onAttachActivity;
	private int type;
	BroadcastReceiver receiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			String action = intent.getAction();
			if (action.equals(MessagePushService.ACTION_COLLECT_FRIEND)) {
				LodingFragmentDialog.dismiss(getFragmentManager());
				String result = intent.getStringExtra("result");
				if (result.equals("0")) {
					ToastUtil.showShort(onAttachActivity, R.string.groupNewFail);
				} else if (result.equals("-1")) {
					ToastUtil.showShort(onAttachActivity,R.string.against__blacklist_operations);
				} else {
					FriendHttpUtil.requestAttentionTofriendsResult(onAttachActivity, cacheCustomerInfoEntity, mAppData);
					adapter.notifyDataSetChanged();
				}
			} else if (action.equals(MessagePushService.ACTION_MESSAGE)) {
				if (intent.hasExtra("senderId")) {
					adapter.notifyDataSetChanged();
				}
			}else if(action.equals(MessagePushService.ACTION_REPEAT_STATE)){//转发
				if ("y".equalsIgnoreCase(intent.getStringExtra("FLAG"))) {
					ToastUtil.showShort(onAttachActivity, "转发成功");
					sendState=1;
					// 好友转发消息需要保存到本地
					if (type == 1) {
						Message message = mHandler.obtainMessage();
						message.obj = new MessageEntity[] {(MessageEntity) intent.getSerializableExtra("picture"),
								(MessageEntity) intent.getSerializableExtra("text") };
						message.what = 1;
						mHandler.sendMessage(message);
					}
					requestHttpSendStatus();
				} else {
					ToastUtil.showShort(onAttachActivity, "转发失败");
					sendState=0;
				}
			}
		}
	};
	private AppData mAppData;
	private CustomerInfoEntity cacheCustomerInfoEntity;
	private int sendState;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.friend_exact_search, null);
		initWidget(view);
		return view;
	}
	@Override
	public void onResume() {
		super.onResume();
		pagesize = 1;
		searchFreind(pagenum, pagesize);
	}
	/**
	 * 转发之后将消息保存
	 */
	final Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// 保存消息到数据库
			if (msg.what == 1) {
				final MessageEntity[] entities = (MessageEntity[]) msg.obj;
				new Thread() {
					public void run() {
						ChatUserHelper helper = ChatUserHelper.getInstance();
						List<String> list = adapter.getSelectIDs();
						if (entities[0] != null) {
							MessageEntity entity = entities[0];
							for (String id : list) {
								entity.setReceiverId(id);
								helper.insertChatMessage(entity);
							}
						}
						if (entities[1] != null) {
							MessageEntity entity = entities[1];
							for (String id : list) {
								entity.setReceiverId(id);
								helper.insertChatMessage(entity);
							}
						}
					};
				}.start();
			}
		}
	};
	
	protected void requestHttpSendStatus() {
		HttpRestClient.doHttpActionForImage(onAttachActivity.getIntent().getStringExtra("picID"), SmartFoxClient.getLoginUserId(),String.valueOf(0) , new AsyncHttpResponseHandler(getActivity()){
			@Override
			public void onSuccess(String content) {
				super.onSuccess(content);
				getActivity().onBackPressed();
			}
		});
	}
	
	@Override
	public void onStop() {
		onAttachActivity.unregisterReceiver(receiver);
		super.onStop();
	}

	@Override
	public void onStart() {
		IntentFilter filter = new IntentFilter();
		filter.addAction(MessagePushService.ACTION_COLLECT_FRIEND);
		filter.addAction(SFSEvent.CONNECTION_LOST);
		filter.addAction(MessagePushService.ACTION_MESSAGE);
		filter.addAction(MessagePushService.ACTION_REPEAT_STATE);
		onAttachActivity.registerReceiver(receiver, filter);
		super.onStart();
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mAppData = HTalkApplication.getAppData();
	}

	private void initWidget(View view) {
		initTitleView(view);
		titleLeftBtn.setOnClickListener(this);
		
		mPullToRefreshListView = (PullToRefreshListView) view.findViewById(R.id.hall);
		mListView = mPullToRefreshListView.getRefreshableView();
		mListView.addFooterView(LayoutInflater.from(onAttachActivity).inflate(	R.layout.list_line_layout, null));
		
		
		if (this.getArguments() != null) { 
			duomeiNum = this.getArguments().getString("num");
		}
		
		adapter = new SearchAdapter<CustomerInfoEntity>(onAttachActivity, FriendExactSearchFragment.this,entities);
		if(onAttachActivity.getIntent().hasExtra("adapter_type")){
			adapter.setChangeMode(true);
			titleRightBtn2.setVisibility(View.VISIBLE);
			titleRightBtn2.setText("确定");
			titleRightBtn2.setOnClickListener(this);
		}else{
			mListView.setOnItemClickListener(FriendExactSearchFragment.this);
		}
		adapter.setType(type);
		adapter.setonClickFriendAttentionListener(FriendExactSearchFragment.this);
		mListView.setAdapter(adapter);
		
		titleTextV.setText(duomeiNum);
		
		mPullToRefreshListView.setOnRefreshListener(this);
		mPullToRefreshListView.setRefreshing();
		
		if (SmartFoxClient.getLoginUserId() == null) {
			ToastUtil.showShort(onAttachActivity, "对不起,请重新登录~");
		} else {
			searchFreind(pagenum, pagesize);
		}
	}

	public static FriendExactSearchFragment getInstance(String str) {
		FriendExactSearchFragment fragment = new FriendExactSearchFragment();
		Bundle bundle = new Bundle();
		bundle.putString("num", str);
		fragment.setArguments(bundle);
		return fragment;
	}

	@Override
	public void onAttach(Activity activity) {
		try {
			onAttachActivity = activity;
			listener = (onBackListener) activity;
		} catch (ClassCastException e) {
			throw new ClassCastException(activity.toString()
					+ " must implement onBackListener");
		}
		super.onAttach(activity);
	}

	@Override
	public void onClick(View v) {
		if (v.getTag() != null && v.getTag() instanceof Integer) {
				int position = (Integer) v.getTag();
				ToChat(entities.get(position),true);
		} else {
			switch (v.getId()) {
			case R.id.title_back:
				listener.onBack();
				break;
			case R.id.title_right2:
				SmartFoxClient.sendRepeatToFriend(String.valueOf(1),adapter.getCusIds(),String.valueOf(getActivity().getIntent().getStringExtra("picID")) );
				break;
			}
		}

	}

	public interface onBackListener {
		void onBack();
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		try {
			FriendHttpUtil.onItemClick(getActivity(), entities.get(position - 1));
		} catch (Exception e) {
		}
	}

	public void ToChat(CustomerInfoEntity entity, Boolean isToInfo) {
		if (SmartFoxClient.getLoginUserId().equals(entity.getId())) {
			Intent intent = new Intent();
			intent.setClass(onAttachActivity, PersonalInformationActivity.class);
			startActivity(intent);
		} else if (entity.isDoctor()) {
			Intent intent = new Intent(onAttachActivity, DoctorMainActivity.class);
			intent.putExtra("id", entity.getId());
			intent.putExtra("type", "1");
			startActivityForResult(intent, 0);
		} else {
			Intent intent = new Intent();
			intent.setClass(onAttachActivity, FriendInformUI.class);
			intent.putExtra("id", entity.getId());
			startActivity(intent);
		}
	}

	@Override
	public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
		pagesize = 1;
		searchFreind(pagenum, pagesize);
	}

	@Override
	public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
		pagesize++;
		searchFreind(pagenum, pagesize);
	}

	public void searchFreind(int pagenum, final int pagesize) {
		type = 0;
		if (onAttachActivity instanceof DoctorExactSearchActivity) {
			type = 1;
		}
		if (type == 0 ) {
			HttpRestClient.doHttpFriendExactSearch(SmartFoxClient.getLoginUserId(), String.valueOf(pagenum),
					String.valueOf(pagesize), duomeiNum, type,new AsyncHander());
		}else {
			HttpRestClient.doHttpDoctorSearchResult(duomeiNum, SmartFoxClient.getLoginUserId(), pagesize, pagenum, new AsyncHander());
		}
		
	}
				
	
	
	class AsyncHander extends AsyncHttpResponseHandler{

		public AsyncHander() {
			super();
		}
		@Override
		public void onSuccess(int statusCode, String content) {
			if (pagesize == 1)entities.clear();
			try {
				JSONObject o = new JSONObject(content);
				if (o.has("error_code")) {
					ToastUtil.showShort(onAttachActivity,o.getString("error_message"));
					return;
				} else {
					entities.addAll(FriendHttpUtil.jsonAnalysisFriendEntity(o.getString("CUSLIST"), true));
					adapter.notifyDataSetChanged();
				}
			} catch (JSONException e) {
				
			}
			super.onSuccess(statusCode, content);
		}

		@Override
		public void onFinish() {
			mPullToRefreshListView.onRefreshComplete();
			super.onFinish();
		}

	
	}

	@Override
	public void onClickFriendAttention(int attentioned,CustomerInfoEntity entity, int positon) {
		cacheCustomerInfoEntity = FriendHttpUtil.requestAttentionTofriends(onAttachActivity, null, entity);
	}
	
}
